package com.ruoyi.user.config;

import com.ruoyi.user.filter.WechatAuthFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 微信安全配置
 * 
 * @author ZhangZhongGen
 */
@Configuration
@Order(1) // 优先级高于主 SecurityConfig
public class WxSecurityConfig {
    
    /**
     * 微信认证过滤器
     */
    @Autowired
    private WechatAuthFilter wechatAuthFilter;
    
    /**
     * 微信专用安全过滤链
     * 只处理微信相关请求路径
     */
    @Bean
    public SecurityFilterChain wxFilterChain(HttpSecurity http) throws Exception {
        return http
            // 只处理/userWeixin路径下的请求
            .antMatcher("/userWeixin/**")
            // CSRF禁用，因为不使用session
            .csrf(csrf -> csrf.disable())
            // 基于token，所以不需要session
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // 请求授权配置
            .authorizeHttpRequests((requests) -> {
                // 登录接口允许匿名访问
                requests.antMatchers("/userWeixin/user/login/**").permitAll()
                    // 除上面外的所有请求都需要认证
                    .anyRequest().authenticated();
            })
            // 添加微信过滤器
            .addFilterBefore(wechatAuthFilter, UsernamePasswordAuthenticationFilter.class)
            .build();
    }
}
